package com.xm.xmapp;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.text.SpannableStringBuilder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xm.xmapp.app.CodeConstant;
import com.xm.xmapp.app.MyAppcation;
import com.xm.xmapp.app.Type;
import com.xm.xmapp.app.Type.F_Main;
import com.xm.xmapp.base.BaseActivity;
import com.xm.xmapp.fragment.MainLeftFragment;
import com.xm.xmapp.myinterface.DisssmissInterFace;
import com.xm.xmapp.myinterface.GetDataInterFace;
import com.xm.xmapp.permissionstools.EasyPermissions;
import com.xm.xmapp.permissionstools.EasyPermissions.PermissionCallbacks;
import com.xm.xmapp.request.bean.RequestCheckIdentity;
import com.xm.xmapp.request.bean.Upload_user_audit_imgRequest;
import com.xm.xmapp.response.bean.ResponseDriverBean;
import com.xm.xmapp.response.bean.ResponseIdCardBean;
import com.xm.xmapp.response.bean.UserInformationStatusBean;
import com.xm.xmapp.tools.ImageTool;
import com.xm.xmapp.tools.Options;
import com.xm.xmapp.tools.ScreenUtils;
import com.xm.xmapp.tools.StringTools;
import com.xm.xmapp.tools.Tools;

public class AuthorizeActivity extends BaseActivity implements OnClickListener, PermissionCallbacks {
	private static final int REQUEST_CODE_QRCODE_PERMISSIONS = 1;
	private ImageView img[] = new ImageView[4];
	private TextView text[] = new TextView[4];
	private int flag;
//	private ResponseIdCardBean.Card mIdCardBean;
//	private ResponseDriverBean.Card mDriverBean;
	private TextView sumbit;
	private Upload_user_audit_imgRequest requestBean;
	private LinearLayout lin;
	private ImageView back;
	private TextView title, no_pass_message;
	private UserInformationStatusBean statusBean;

	@Override
	public Object dataChang(int type, Object data) {

		switch (type) {
		case Type.A_Authorize.GET_BITMAP: {
			Bitmap bitmap = (Bitmap) data;
			switch (this.flag) {
			case 0:
				img[flag].setImageBitmap(bitmap);
				requestBean.identity_front_img = "suffix:jpg;base64;" + ImageTool.Bitmap2StrByBase64(bitmap);
				break;
			case 1:
				img[this.flag].setImageBitmap(bitmap);
				requestBean.driving_licence_front_img = "suffix:jpg;base64;" + ImageTool.Bitmap2StrByBase64(bitmap);
				break;
			default:
				break;
			}
			break;
		}
		case Type.A_Authorize.GET_DATA: {

			switch (this.flag) {
			case 0:
//				mIdCardBean = (ResponseIdCardBean.Card) data;
				break;
			case 1:
//				mDriverBean = (ResponseDriverBean.Card) data;
				break;

			default:
				break;
			}

			break;
		}
		default:
			break;
		}
		return super.dataChang(flag, data);
	}

	@Override
	protected void onStart() {
		super.onStart();
		requestCodeQRCodePermissions();
	}

	private void requestCodeQRCodePermissions() {

		String[] perms = { android.Manifest.permission.CAMERA };
		if (!EasyPermissions.hasPermissions(this, perms)) {
			EasyPermissions.requestPermissions(this, "个人认证需要打开相机权限", REQUEST_CODE_QRCODE_PERMISSIONS, perms);
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_rz);
	}

	@Override
	public void initView() {

		img[0] = (ImageView) findViewById(R.id.img0);
		img[1] = (ImageView) findViewById(R.id.img1);
		img[2] = (ImageView) findViewById(R.id.img2);
		img[3] = (ImageView) findViewById(R.id.img3);
		text[0] = (TextView) findViewById(R.id.text0);
		text[1] = (TextView) findViewById(R.id.text1);
		text[2] = (TextView) findViewById(R.id.text2);
		text[3] = (TextView) findViewById(R.id.text3);

		sumbit = (TextView) findViewById(R.id.sumbit);
		back = (ImageView) findViewById(R.id.back);
		lin = (LinearLayout) findViewById(R.id.lin);
		title = (TextView) findViewById(R.id.title);
		no_pass_message = (TextView) findViewById(R.id.no_pass_message);
	}

	@Override
	public void initData() {
		title.setText("实名认证");
		statusBean = (UserInformationStatusBean) getIntent().getSerializableExtra("bean");
		if (statusBean == null) {
			statusBean = new UserInformationStatusBean();
			statusBean.user_information_status = -1;
		}
		/**
		 * -1是待认证，0是认证不通过
		 */
		if (statusBean.user_information_status == 0 && statusBean.no_pass_message != null
				&& !statusBean.no_pass_message.equals("")) {
			lin.setVisibility(View.VISIBLE);
			no_pass_message.setText(statusBean.no_pass_message);
		} else {
			lin.setVisibility(View.GONE);
		}
		requestBean = new Upload_user_audit_imgRequest();
	}

	@Override
	public void initEvent() {

		// statusBean.user_checked_img_info = null;
		if (statusBean.user_information_status == -1) {
			img[0].setOnClickListener(this);
			img[1].setOnClickListener(this);
			img[2].setOnClickListener(this);
			img[3].setOnClickListener(this);
		} else {
			if (statusBean.user_checked_img_info != null) {
				sumbit.setText("重新提交");
				String url;
				SpannableStringBuilder style = null;
				String str_text;
				String str;
				url = statusBean.user_checked_img_info.identity_front_url;
				if (url.equals("")) {
					str = "\n(不通过：" + statusBean.user_checked_img_info.identity_front_false_reason + ")";
					str_text = "身份证正面" + str;
					style = StringTools.getStyle(str_text.length() - str.length(), str, str_text, getResources()
							.getDimensionPixelOffset(R.dimen.smallsize3), Color.RED);
					text[0].setText(style);
					img[0].setOnClickListener(this);
				} else {
					text[0].setText("身份证正面");
					DisplayImageOptions options = Options.getListOptions(R.mipmap.tongguo_moren);
					ImageLoader.getInstance().displayImage(url, img[0], options);

				}

				url = statusBean.user_checked_img_info.driving_licence_front_img_url;
				if (url.equals("")) {
					str = "\n(不通过：" + statusBean.user_checked_img_info.driving_licence_front_img_false_reason + ")";
					str_text = "驾驶证正面" + str;
					style = StringTools.getStyle(str_text.length() - str.length(), str, str_text, getResources()
							.getDimensionPixelOffset(R.dimen.smallsize3), Color.RED);
					text[1].setText(style);
					img[1].setOnClickListener(this);
				} else {
					text[1].setText("驾驶证正面");
					DisplayImageOptions options = Options.getListOptions(R.mipmap.tongguo_moren);
					ImageLoader.getInstance().displayImage(url, img[1], options);
				}

				url = statusBean.user_checked_img_info.driving_licence_counterpart_img_url;
				if (url.equals("")) {
					str = "\n(不通过：" + statusBean.user_checked_img_info.driving_licence_counterpart_img_false_reason
							+ ")";
					str_text = "驾驶证附件正面" + str;
					style = StringTools.getStyle(str_text.length() - str.length(), str, str_text, getResources()
							.getDimensionPixelOffset(R.dimen.smallsize3), Color.RED);
					text[2].setText(style);
					img[2].setOnClickListener(this);
				} else {
					text[2].setText("驾驶证附件正面");
					DisplayImageOptions options = Options.getListOptions(R.mipmap.tongguo_moren);
					ImageLoader.getInstance().displayImage(url, img[2], options);
				}

				url = statusBean.user_checked_img_info.people_and_identity_img_url;
				if (url.equals("")) {
					str = "\n(不通过：" + statusBean.user_checked_img_info.people_and_identity_img_false_reason + ")";
					str_text = "手持身份证照片" + str;
					style = StringTools.getStyle(str_text.length() - str.length(), str, str_text, getResources()
							.getDimensionPixelOffset(R.dimen.smallsize3), Color.RED);
					text[3].setText(style);
					img[3].setOnClickListener(this);
				} else {
					text[3].setText("手持身份证照片");
					DisplayImageOptions options = Options.getListOptions(R.mipmap.tongguo_moren);
					ImageLoader.getInstance().displayImage(url, img[3], options);
				}
			} else {
				img[0].setOnClickListener(this);
				img[1].setOnClickListener(this);
				img[2].setOnClickListener(this);
				img[3].setOnClickListener(this);
			}
		}
		sumbit.setOnClickListener(this);
		back.setOnClickListener(this);
	}

	@Override
	public void onClick(View arg0) {

		switch (arg0.getId()) {
		case R.id.img0:
			flag = 0;
			intent = new Intent(getApplicationContext(), TakePhotoActivity.class);
			intent.putExtra("isIdCard", true);
			startActivityForResult(intent, CodeConstant.TakePhoto); // 用户点击了从相机获取

			break;
		case R.id.img1:
			flag = 1;
			intent = new Intent(getApplicationContext(), TakePhotoActivity.class);
			intent.putExtra("isIdCard", false);
			startActivityForResult(intent, CodeConstant.TakePhoto); // 用户点击了从相机获取
			break;
		case R.id.img2:
			flag = 2;
			doTakePhoto();
			break;
		case R.id.img3:
			flag = 3;
			doTakePhoto();
			break;
		case R.id.sumbit: {
			if (statusBean.user_information_status == -1) {
				if (requestBean.identity_front_img == null || requestBean.driving_licence_front_img == null
						|| requestBean.driving_licence_counterpart_img == null
						|| requestBean.people_and_identity_img == null) {
					Tools.showMessage("请先添加完照片");
				} else {
					upload_user_audit_imgRequest();
				}
			} else {

				if (statusBean.user_checked_img_info != null) {
					String url;
					url = statusBean.user_checked_img_info.identity_front_url;
					if (url.equals("") && requestBean.identity_front_img == null) {
						Tools.showMessage("请先添加完未通过的照片");
						return;
					}

					url = statusBean.user_checked_img_info.driving_licence_front_img_url;
					if (url.equals("") && requestBean.driving_licence_front_img == null) {
						Tools.showMessage("请先添加完未通过的照片");
						return;
					}

					url = statusBean.user_checked_img_info.driving_licence_counterpart_img_url;
					if (url.equals("") && requestBean.driving_licence_counterpart_img == null) {
						Tools.showMessage("请先添加完未通过的照片");
						return;
					}

					url = statusBean.user_checked_img_info.people_and_identity_img_url;
					if (url.equals("") && requestBean.people_and_identity_img == null) {
						Tools.showMessage("请先添加完未通过的照片");
						return;
					}

					upload_user_audit_imgRequest();
				} else {
					if (requestBean.identity_front_img == null || requestBean.driving_licence_front_img == null
							|| requestBean.driving_licence_counterpart_img == null
							|| requestBean.people_and_identity_img == null)
						Tools.showMessage("请先添加完照片");
					else
						upload_user_audit_imgRequest();
				}
			}
		}
			break;

		case R.id.back:
			finish();
			break;
		default:
			break;
		}
	}

	private void upload_user_audit_imgRequest() {
		

//		if (mDriverBean != null && mIdCardBean != null
//				&& !mDriverBean.license_number.equals(mIdCardBean.id_card_number)) {
//			Tools.showMessage("身份证与驾驶证信息不符，请重新拍摄");
//			return;
//		}
//
//		if (mIdCardBean != null) {
//			requestBean.identity = mIdCardBean.id_card_number;
//			requestBean.identity_name = mIdCardBean.name;
//		}
//		setDriving_license_expire();

		promptDialog.show();
		final DisssmissInterFace mErrorListener = new DisssmissInterFace() {

			@Override
			public void putError(VolleyError error) {
				promptDialog.dismiss();
			}
		};

		final GetDataInterFace<String> mListener = new GetDataInterFace<String>() {

			@Override
			public void onResponse(String response) {
				promptDialog.dismiss();
				Tools.showMessage("资料上传成功");
				MyAppcation.getMyAppcation().notifyDataSetChanged(MainLeftFragment.class, F_Main.AUTHORIZE);
				finish();
			}
		};

//		if (statusBean.user_information_status == -1 && mIdCardBean != null) {// 首次上传，判断身份证
//
//			RequestCheckIdentity mRequestCheckIdentity = new RequestCheckIdentity();
//			mRequestCheckIdentity.identity = mIdCardBean.id_card_number;
//			MyAppcation.getMyAppcation().getPostData(this, mRequestCheckIdentity, new GetDataInterFace<String>() {
//
//				@Override
//				public void onResponse(String response) {
//					MyAppcation.getMyAppcation().getPostData(this, requestBean, mListener, mErrorListener);
//				}
//			}, mErrorListener);
//
//		} else {
			MyAppcation.getMyAppcation().getPostData(this, requestBean, mListener, mErrorListener);
//		}
	}

	/**
	 * 设置驾照过期日期
	 */
//	private void setDriving_license_expire() {
//		if (mDriverBean != null) {
//
//			if (mDriverBean.valid_date != null) {
//				String[] str = mDriverBean.valid_date.split("至");
//				if (str.length > 1) {
//					requestBean.driving_license_expire = str[1];
//				} else {
//					return;
//				}
//			} else {
//				// valid_from valid_for
//				try {
//
//					SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); // 日期格式
//					Date startDate = dateFormat.parse(mDriverBean.valid_from); // 指定日期
//					Calendar calendar = Calendar.getInstance();
//					calendar.setTime(startDate);
//					String strYears = mDriverBean.valid_for;
//					strYears = strYears.replaceAll("年", "");
//					int years = Integer.parseInt(strYears);
//					calendar.add(Calendar.YEAR, years);
//					requestBean.driving_license_expire = dateFormat.format(calendar.getTime());
//
//				} catch (Exception e) {
//					Tools.showMessage("异常错误");
//					return;
//				}
//			}
//
//		}
//	}

	/** 拍照获取相片 **/
	private void doTakePhoto() {

		intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); // 调用系统相机
		Uri imageUri = Uri.fromFile(new File(CodeConstant.PhotoPath));// 指定照片保存路径（SD卡），image.jpg为一个临时文件，每次拍照后这个图片都会被替换
		intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
		startActivityForResult(intent, CodeConstant.TakePhoto); // 用户点击了从相机获取

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case CodeConstant.TakePhoto:
				String status = Environment.getExternalStorageState();
				if (status.equals(Environment.MEDIA_MOUNTED)) { // 是否有SD卡
					Bitmap bitmap = null;
					int width = ScreenUtils.getScreenWidth(AuthorizeActivity.this);
					int height = ScreenUtils.getScreenHeight(AuthorizeActivity.this);
					if (width > 720) {
						bitmap = ImageTool.getSmallBitmap(CodeConstant.PhotoPath, 720, 1280);
					} else {
						bitmap = ImageTool.getSmallBitmap(CodeConstant.PhotoPath, width, height);
					}

					if (bitmap != null) {
						img[flag].setImageBitmap(bitmap);
						switch (flag) {
						case 0:
							requestBean.identity_front_img = "suffix:jpg;base64;"
									+ ImageTool.Bitmap2StrByBase64(bitmap);

							break;
						case 1:
							requestBean.driving_licence_front_img = "suffix:jpg;base64;"
									+ ImageTool.Bitmap2StrByBase64(bitmap);

							break;
						case 2:
							requestBean.driving_licence_counterpart_img = "suffix:jpg;base64;"
									+ ImageTool.Bitmap2StrByBase64(bitmap);

							break;
						case 3:
							requestBean.people_and_identity_img = "suffix:jpg;base64;"
									+ ImageTool.Bitmap2StrByBase64(bitmap);

							break;
						default:
							break;
						}
					}

				} else {
					Tools.showMessage("没有SD卡");
				}
				break;

			default:
				break;
			}
		}

	}

	@Override
	public void onPermissionsGranted(int requestCode, List<String> perms) {

	}

	@Override
	public void onPermissionsDenied(int requestCode, List<String> perms) {

	}

	@Override
	public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
		EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
	}
}
